package com.example.administrator.szb.activity;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.bumptech.glide.Glide;
import com.example.administrator.szb.R;
import com.example.zhouwei.library.CustomPopWindow;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.api.OnRefreshLoadmoreListener;

import java.util.ArrayList;
import java.util.HashMap;

import com.example.administrator.szb.adapter.BaseAdapter;
import com.example.administrator.szb.activity.base.BaseActivity;
import com.example.administrator.szb.bean.MyZXBean;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import com.example.administrator.szb.tinkerutil.SampleApplicationLike;
import com.example.administrator.szb.http.HttpUtil;
import com.example.administrator.szb.http.URLAddress;

/**
 * Created by D N on 2017/9/29.
 */

public class MyZXActivity extends BaseActivity {
    @Bind(R.id.my_zx_fh)
    ImageView myZxFh;
    @Bind(R.id.my_zx_bj)
    ImageView myZxBj;
    @Bind(R.id.my_zx_recyclerview)
    RecyclerView myZxRecyclerview;
    @Bind(R.id.zx_swiptrefreshlayout)
    SmartRefreshLayout zxSwiptrefreshlayout;
    private CustomPopWindow popWindow;


    MyZXBean zxBean;
    BaseAdapter<MyZXBean.DataBean> adapter;

    int current_page = 1 ;
    int per_page = 10;

    View footerview;
    ArrayList<MyZXBean.DataBean> mdata = new ArrayList<>();

    int wz=0;//用于判断是否加了head,而导致position 的位置不对
    View error_head;
    private boolean isFirstEnter = true;


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.my_zx_activity);
        SampleApplicationLike.getActivitiesInstance().add(this);
        ButterKnife.bind(this);
        //requestZX();
        footerview = LayoutInflater.from(this).inflate(R.layout.view_wd_footer, null);
        footerview.setVisibility(View.INVISIBLE);

        initView();
    }
    private void initView() {
        initRefresh();
        //initRecyclerview();
    }
    private void initRefresh() {
//        zxSwiptrefreshlayout.setColorSchemeResources(R.color.zhutise);
//        zxSwiptrefreshlayout.post(new Runnable() {
//            @Override
//            public void run() {
//                current_page = 1;
//                zxSwiptrefreshlayout.setRefreshing(true);
//                requestZX(0);
//            }
//        });
//
//        zxSwiptrefreshlayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
//            @Override
//            public void onRefresh() {
//                current_page = 1;
//                zxSwiptrefreshlayout.setRefreshing(true);
//                requestZX(0);
//            }
//        });

        if (isFirstEnter) {
            isFirstEnter = false;
            zxSwiptrefreshlayout.autoRefresh();
        }
        zxSwiptrefreshlayout.setEnableLoadMore(true);//是否启用上拉加载功能
        zxSwiptrefreshlayout.setEnableLoadMoreWhenContentNotFull(true);//是否在列表不满一页时候开启上拉加载功能


        zxSwiptrefreshlayout.setOnRefreshLoadmoreListener(new OnRefreshLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                //refreshlayout.setLoadmoreFinished(false);//恢复上拉状态
                // Toasts.show(getActivity(), "加载更多啊", Toast.LENGTH_SHORT);
                requestZX(1);
            }

            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                current_page = 1;
                requestZX(0);
                //refreshlayout.finishRefresh();
            }
        });
    }

    private void requestZX(final int isRefreshOrMore) {
        HashMap<String, String> map = new HashMap<>();
        map.put("code", HttpUtil.getParam());
        map.put("id", SampleApplicationLike.getUserloginInstance().getId() + "");
        map.put("current_page",current_page + "");
        map.put("per_page", per_page + "");
        String url = URLAddress.URLBASE + URLAddress.URL_ZXLB;
        HttpUtil.RequestGsonPost(SampleApplicationLike.getQueueInstance(), Request.Method.POST, MyZXBean.class, url, map, new Response.Listener() {
            @Override
            public void onResponse(Object response) {
                zxBean = (MyZXBean) response;
                if (zxBean.getResult() == 1){
                    //initRecyclerview();
                    if (isRefreshOrMore == 0) {
                        mdata.clear();
                        mdata.addAll(zxBean.getData());
                        zxSwiptrefreshlayout.finishRefresh();
                        current_page = current_page+1;
                        initRecyclerview();
                        // Toasts.show(getActivity(), "刷新成功", Toast.LENGTH_SHORT);
                    }else if(isRefreshOrMore == 1){
                        if (zxBean.getData().size()>0){
                            current_page = current_page+1;
                            mdata.addAll(zxBean.getData());
                        }else{
                            //Toasts.show(MyZXActivity.this, "没有数据了", Toast.LENGTH_SHORT);
                        }


                        zxSwiptrefreshlayout.finishLoadmore();
                    }
                    adapter.notifyDataSetChanged();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
    }

    private void initRecyclerview() {
        myZxRecyclerview.setLayoutManager(new LinearLayoutManager(this));
        adapter = new BaseAdapter<MyZXBean.DataBean>(this, mdata) {
            @Override
            public void convert(int position, BaseViewHolder holder, MyZXBean.DataBean listBean) {
                ((TextView) holder.getView(R.id.textView58)).setText(listBean.getAuthor());
                ((TextView) holder.getView(R.id.textView59)).setText(listBean.getCreate_time());
                ((TextView) holder.getView(R.id.textView162)).setText(listBean.getTitle());
                if (listBean.getType() == 1) {
                    (holder.getView(R.id.imageView24)).setVisibility(View.GONE);
                } else {
                    (holder.getView(R.id.imageView24)).setVisibility(View.VISIBLE);
                }

                ((TextView) holder.getView(R.id.textView163)).setText(listBean.getCollect_count() + "人浏览");

                if (TextUtils.isEmpty(listBean.getImage())) {
                    (holder.getView(R.id.imageView23)).setVisibility(View.GONE);
                } else {
                    Glide.with(MyZXActivity.this).load(listBean.getImage()).into(((ImageView) holder.getView(R.id.imageView23)));
                }

                if (!TextUtils.isEmpty(listBean.getHeadImg())) {
                    Glide.with(MyZXActivity.this).load(listBean.getHeadImg()).into(((ImageView) holder.getView(R.id.imageView22)));
                }
            }

            @Override
            public int getLayoutId(int viewType) {
                return R.layout.view_zx_item;
            }
        };
        adapter.setOnItemClickListener(new BaseAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                Intent intent = new Intent(MyZXActivity.this, WebViewActivity.class);
                intent.putExtra("wz_id", zxBean.getData().get(position).getId());
                intent.putExtra("title", zxBean.getData().get(position).getTitle());
                intent.putExtra("image", zxBean.getData().get(position).getImage());
                startActivity(intent);
            }
        });


        if (mdata.size() == 0){
            error_head = LayoutInflater.from(MyZXActivity.this).inflate(R.layout.view_item_error, myZxRecyclerview, false);
            ((TextView)error_head.findViewById(R.id.text_view_error)).setText("尚未发布资讯");
            adapter.addHeaderView(error_head);
        }else{
//            com.example.administrator.szb.adapter.addFootView(footerview);
//            loadMore();//开启加载更多监听
        }


        myZxRecyclerview.setAdapter(adapter);

    }



    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @OnClick({R.id.my_zx_fh, R.id.my_zx_bj})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.my_zx_fh:
                finish();
                break;
            case R.id.my_zx_bj:
                showPopupwindow(R.layout.view_popupwindow_myzx, 0);
                break;
        }
    }

    /**
     * 初始化popupwindow弹出框
     */
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    private void showPopupwindow(int view_layout_id, int rootview_layout_id) {
        View popwindow_view = LayoutInflater.from(this).inflate(view_layout_id, null);
        //View rootview = LayoutInflater.from(this).inflate(rootview_layout_id, null);

        //如果不是进度框，就执行底部弹出
        if (view_layout_id != R.layout.view_progressbar) {
            popWindow = new CustomPopWindow.PopupWindowBuilder(this)
                    .setView(popwindow_view)//显示的布局，还可以通过设置一个View
                    .create()//创建PopupWindow
                    .showAsDropDown(myZxBj, 0, 50);
            // .showAtLocation(rootview, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
            handleLogic(popwindow_view, popWindow);//处理popupwindow 中的item点击事件
        }
        //显示PopupWindow

    }


    /**
     * 处理弹出显示内容、点击事件等逻辑
     *
     * @param contentView
     */
    private void handleLogic(View contentView, final CustomPopWindow mCustomPopWindow) {
        View.OnClickListener listener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mCustomPopWindow != null) {
                    mCustomPopWindow.dissmiss();
                }
                switch (v.getId()) {
                    case R.id.view_my_zx_twzx:
                        startActivity(new Intent(MyZXActivity.this, TWFBActivity.class));
                        break;
                    case R.id.view_my_zx_spzx:
                        startActivity(new Intent(MyZXActivity.this, SPFBActivity.class));
                        break;
                }
                //Toasts.show(MingPianActivity.this, showContent, Toast.LENGTH_SHORT);
            }
        };
        contentView.findViewById(R.id.view_my_zx_twzx).setOnClickListener(listener);
        contentView.findViewById(R.id.view_my_zx_spzx).setOnClickListener(listener);

    }

    @Override
    protected void onRestart() {
        super.onRestart();
        current_page = 1;
        requestZX(0);
    }
}
